// _initPackage
let engine_adapt_init = () => {
    console.log("engine_adapt_init")

    let func = Vue.component
    Vue.component = function () {
        let forObj
        forObj = function (obj, head) {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    console.log(`${head} 【${key}(${typeof obj[key]})】:${obj[key]}`)
                    if (typeof obj[key] === 'object') {
                        forObj(obj[key], `\t${head}`)
                    }
                }
            }
        }
        if (arguments.length >= 2) {
            let output = ""
            console.log((arguments))
            let obj = arguments[1]
            forObj(obj, "\t")
        }
        func(...arguments)
    }
    return

    // bundle resources
    let bundle_init_old = cc.AssetManager.Bundle.prototype.init
    cc.AssetManager.Bundle.prototype.init = function () {
        bundle_init_old.apply(this, arguments)
        if (this.name === cc.AssetManager.BuiltinBundleName.RESOURCES) {
            var assetInfos = this._config.assetInfos;
            for (var packUuid in arguments[0].packs) {
                var assetInfo = assetInfos.get(packUuid);
                if (assetInfo) {
                    assetInfo.ext = ".zipJson"
                }
            }
        }
    }
    var downloadZipJson = function (url, options, onComplete) {
        options.responseType = "arraybuffer";
        cc.assetManager.downloader.downloadFile(url, options, options.onFileProgress, function (err, zipData) {
            if (!err) {
                try {
                    let newZip = new JSZip()
                    newZip.loadAsync(zipData).then((zipObj) => {
                        Object.keys(zipObj.files).forEach((key) => {
                            //@ts-ignore
                            zipObj.files[key].async("string").then((data) => {
                                data = JSON.parse(data)
                                onComplete && onComplete(err, data)
                            })
                        });

                    })
                }
                catch (e) {
                    err = e;
                    onComplete && onComplete(err, data);
                }
            } else {
                onComplete && onComplete(err, data);
            }
        });
    };
    function createJsonAsset(id, data, options, onComplete) {
        let out = new cc.JsonAsset();
        out.json = data;
        onComplete && onComplete(null, out);
    }
    cc.assetManager.factory.register(".zipJson", createJsonAsset)
    cc.assetManager.downloader.register(".zipJson", downloadZipJson)
    cc.assetManager.packManager.register(".zipJson", cc.assetManager.packManager.unpackJson)

    // spine      
    async function parseSpine(zipData) {
        return new Promise((resolve) => {
            let newZip = new JSZip()
            let _json = null
            let _atlas = null
            let _textureNames = []
            let _texture = null

            let isSuccess = (resolve) => {
                if (!_json || !_atlas || !_texture) return null
                let spineAsset = new sp.SkeletonData();
                spineAsset.skeletonJson = _json
                spineAsset.atlasText = _atlas
                spineAsset.textures = [_texture]
                spineAsset.textureNames = _textureNames
                return resolve(spineAsset)
            }

            newZip.loadAsync(zipData).then((zipObj) => {
                Object.keys(zipObj.files).forEach((key) => {
                    let ext = cc.path.extname(key)
                    switch (ext) {
                        case ".json": {
                            zipObj.files[key].async("string").then((data) => {
                                _json = JSON.parse(data)
                                isSuccess(resolve)
                            })
                        } break
                        case ".atlas": {
                            zipObj.files[key].async("text").then((data) => {
                                _atlas = data
                                isSuccess(resolve)
                            })
                        } break
                        case ".png": {
                            if (cc.sys.platform == cc.sys.WECHAT_GAME) {
                                zipObj.files[key].async("base64").then((data) => {
                                    cc.assetManager.parser.parse(key, 'data:image/png;base64,' + data, ".png", { __flipY: false, __premultiplyAlpha: false }, (err, img) => {
                                        let texture = new cc.Texture2D()
                                        texture.initWithData(img, cc.Texture2D.PixelFormat.RGBA8888, img.width, img.height)
                                        _texture = texture
                                        _textureNames.push(key)
                                        isSuccess(resolve)
                                    })
                                })
                            } else {
                                zipObj.files[key].async("blob").then((data) => {
                                    cc.assetManager.parser.parse(key, data, ".png", { __flipY: false, __premultiplyAlpha: false }, (err, img) => {
                                        cc.assetManager.factory.create(key, img, ".png", null, (err, out) => {
                                            _texture = out
                                            _textureNames.push(key)
                                            isSuccess(resolve)
                                        })
                                        // let texture = new cc.Texture2D()
                                        // texture.initWithData(img, cc.Texture2D.PixelFormat.RGBA8888, img.width, img.height)
                                        // _texture = texture
                                        // _textureNames.push(key)
                                        // isSuccess(resolve)
                                    })
                                })
                            }
                        } break
                    }
                });
            })
        })
    }

    async function parseZipSpine(file, options, onComplete) {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            const fs = wx.getFileSystemManager()
            fs.readFile({
                filePath: file,
                success(res) {
                    parseSpine(res.data).then((spineData) => {
                        onComplete && onComplete(null, spineData)
                    })
                },
                fail(res) {
                    console.error(JSON.stringify(res))
                }
            })
        } else {
            parseSpine(file).then((spineData) => {
                onComplete && onComplete(null, spineData)
            })
        }
    }
    function factoryZipSpine(id, data, options, onComplete) {
        onComplete && onComplete(null, data)
    }

    cc.assetManager.factory.register(".zipspine", factoryZipSpine)
    cc.assetManager.downloader.register(".zipspine", cc.assetManager.downloader._downloaders[".binary"])
    cc.assetManager.parser.register(".zipspine", parseZipSpine)
}


// engine_adapt_init()
